// pages/newPage/newPage.js
var app = getApp()
var ConstantData = require('../../../common/constant_data.js')
var BLELocker = require('../../../common/BLELocker.js')
var connectUtil = require('../../../utils/ble-dfu/connect.js');
var downloadUtil = require('../../../utils/ble-dfu/download.js');
var commonUtil = require('../../../common/common.js')
var util = require('../../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading_show: true,
    scanTime: 1500,
    leaseSuc: false,
    equId: 0,
    rent: 0,
    backtime: "",
    opentime: "",
    tipImg: false,
    voiceTempFilePath: '/image/backSuc.mp3',
    duanyuyin: '/image/duanyuyin.mp3',
    yuyinzujie: '/image/successyuyin.mp3',
    showTitle: true,
    beeBannerHeight: 0,
    beeBannerConfig: null,
    beeModalConfig: null,
    showBeeModal: false,
    wxSubMsgTipAlert: false,
    isSubOffical: true,
    officalSubImg: ConstantData.CONSTATNT_DATA.OFFICAL_SUB_IMG_URL
  },

  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function () {
    var that = this

    if (that.data.leaseSuc) {
      app.goFollowMp(-200004, '关注公众号-租借成功')
    } else if (that.data.backtime) {
      app.goFollowMp(-200005, '关注公众号-归还成功')
    }
  },

  disabledTouch() {
    return false;
  },

  closeBeeModal() {
    this.setData({
      showBeeModal: false
    })
  },

  clickBeeModal() {
    wx.navigateToMiniProgram({
      appId: this.data.beeModalConfig.appId,
      path: this.data.beeModalConfig.path,
      success(res) {
        console.log('【小蜜蜂广告跳转】跳转成功：' + JSON.stringify(res))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30001, '归还成功-小蜜蜂弹窗广告', 'success')
      },
      fail(error) {
        console.log('【小蜜蜂广告跳转】跳转失败：' + JSON.stringify(error))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30001, '归还成功-小蜜蜂弹窗广告', 'fail')
      }
    })
  },

  clickBeeBanner() {
    wx.navigateToMiniProgram({
      appId: this.data.beeBannerConfig.appId,
      path: this.data.beeBannerConfig.path,
      success(res) {
        console.log('【小蜜蜂广告跳转】跳转成功：' + JSON.stringify(res))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'success')
      },
      fail(error) {
        console.log('【小蜜蜂广告跳转】跳转失败：' + JSON.stringify(error))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'fail')
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isSubOffical: app.globalData.isSubOffical
    })
    console.log(wx.getStorageSync('no_pay_deposit'), 'ksadddddddddddddddddddddddddjfklhjdskahfkjdshfkjdsf', options)
    getApp().hideLoading();
    let that = this;
    let userId = wx.getStorageSync('user_id');
    let tipPage = options.pt == 'lease' ? 'rent' : 'back';
    that.setData({
      lockType: options.lockType
    })
    that.data.tipPage = tipPage;
    that.data.userId = userId;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/weixin/tip_info',
        header: header,
        method: 'post',
        data: {
          actType: 'wx',
          tipPage: tipPage,
          userId: userId
        },
        success: function (res) {
          let resData = res.data;
          if (resData) {
            let adType = resData.skipType == 'mini' ? (resData.tipType == 'wx' ? 2 : 1) : 3;
            that.setData({
              tipImg: true, //flg,活动的开启和关闭
              adId: resData.id, //用来唯一标识广告的id，参考说明文档中的广告标题
              adImgUrl: that.getCurrentUrl(resData.tipImg), //广告图片
              adType: adType, // 1是支付宝小程序；2是微信小程序；3是h5页面
              adPath: resData.skipUrl, //跳转地址
            })
            that.recordAd('read');
          }
        },
        fail: function (res) {
          console.log(res)
        }
      })
    });

    app.globalData.isLeaseCon = false;
    let version = wx.getSystemInfoSync().SDKVersion;
    let miniFileIsOk = commonUtil.compareVersion(version, ConstantData.CONSTATNT_DATA.FILE_SYSTEM_MANAGER_MIN_SDK_VER) >= 0;

    if (options.backSucVoiceUrl) {
      this.data.voiceTempFilePath = options.backSucVoiceUrl;
    }
    let isAutoRefund = options.depositBackSuc ? true : false;
    let defaultBackDesc = isAutoRefund ? '押金已原路退回，请注意查看消息提示。' : '如要退回押金，请到首页点击退押金申请退押金!';
    //链条锁控制盒不提示用户再次扫码归还
    let isShowLeaseDesc = !options.backtime && this.data.lockType && (this.data.lockType.indexOf("链条") == -1 || this.data.lockType.indexOf("NB") == -1);
    this.setData({
      leaseSuc: options.pt == 'lease',
      isShowLeaseDesc: isShowLeaseDesc,
      equId: options.equId,
      rent: options.rent ? options.rent : 0,
      costtime: options.costtime ? options.costtime : '',
      backtime: options.backtime ? options.backtime.replace(".0", "") : "",
      opentime: options.opentime ? options.opentime.replace(".0", "") : "",
      backSucDesc: options.backSucDesc ? options.backSucDesc : defaultBackDesc,
      depositBackSuc: isAutoRefund,
    })

    if (options.isVoice) {
      if (this.data.leaseSuc) {
        this.registerAudioContexted();
      } else {
        this.registerAudioContext();
      }
    }

    let isPayUpgradeFlg = app.globalData.isPayUpgrade ? this.data.backtime : (this.data.rent == 0 && this.data.backtime);
    let isLockUpgradeFlg = app.globalData.isLockUpgrade ? !this.data.backtime : false;
    let isUpgrade = isPayUpgradeFlg || isLockUpgradeFlg;
    console.log("文件系统文件接口是否可用>>>>>", miniFileIsOk, isUpgrade + "-pay", app.globalData.allowUpgradeOtherMac + "-otherMac");

    let pileId = wx.getStorageSync('pileId');
    if (this.data.equId == '90777' && pileId) {
      this.setData({
        pileId: pileId
      })
    } else if (miniFileIsOk && isUpgrade && (
        (app.globalData.isAllowUpgrade && app.globalData.lastDriveVer != app.globalData.driveFirmwareVer) ||
        app.globalData.allowUpgradeOtherMac)) {
      //归还且已支付成功的进行文件升级,且版本号值不同（防止重复升级）
      commonUtil.recordErrorInfo(ConstantData.CONSTATNT_DATA.LOG_TYPE_UPGRADE_DRIVE_START, "开始升级:" + app.globalData.upgradeMac, app.globalData.upgradeMac);
      console.log("开始升级驱动文件。。。");
      //非陪护床的控制盒可以走静默升级,只做升级不处理其他业务
      app.globalData.isLeaseCon = false;

      var mac = app.globalData.upgradeMac;
      downloadUtil.downloadZip().then(() => {
        app.globalData.isUpgradeing = true;
        console.log("开始扫描设备信息-->", mac)
        downloadUtil.unzipFile();
        connectUtil.scanDevice(mac);
      }, (res) => {
        console.error("下载失败---->", res, mac)
      });
      setTimeout(function () {
        that.setData({
          loading_show: false
        });
      }, 60000);
      return;
    }

    this.getBasicConfigInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let that = this;
    // if (that.data.tipPage == 'back') {
    //   setTimeout(()=>{
    //     that.registerAudioContext();
    //   },that.data.scanTime - 500)
    // }else{
    //   console.log(that.data.lockType,'that.data.lockType')
    //   setTimeout(()=>{
    //     if(that.data.lockType != '链条锁'){
    //       that.registerAudioContexted();
    //     }
    //   },that.data.scanTime - 500)
    // }

    wx.createSelectorQuery().in(this).select('.bottom-banner').boundingClientRect().exec((res) => {
      if (res && res[0]) {
        this.setData({
          beeBannerHeight: res[0].height
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //重定向到某一页面
  toNext: function () {
    var that = this;
    if (that.data.leaseSuc) {
      let tmplIds = ['Ojc2ykpjZCmudn04IfG5M-3_1SBwzkrrSGHy7B68_Ig', 'neMTKZJgUrp9cHl4OVE9pTRiPs3nWYtGR2SHVY1ix58'];
      if (wx.requestSubscribeMessage) {
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            console.log('【订阅消息】弹出订阅消息成功...' + JSON.stringify(res));
            let acceptIds = [];
            for (let i = 0; i < tmplIds.length; i++) {
              res[tmplIds[i]] == 'accept' ? acceptIds[i] = 1 : acceptIds[i] = 0;
            }
            app.executeRequest((header) => {
              wx.request({
                url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
                method: 'post',
                header: header,
                data: {
                  acceptIds: JSON.stringify(acceptIds)
                }
              })
            })
          },
          fail(error) {
            console.log('【订阅消息】弹出订阅消息失败...' + JSON.stringify(error));
          },
          complete(res) {
            console.warn('【订阅消息】弹出订阅消息完成...' + JSON.stringify(res));
            wx.redirectTo({
              url: '../../user_record/lease/user_lease',
            })
          }
        })
      } else {
        wx.redirectTo({
          url: '../../user_record/lease/user_lease',
        })
      }
    } else {
      wx.redirectTo({
        url: '../../user_record/lease/user_lease',
      })
    }
  },
  toIndex: function () {
    app.globalData.userStay = false;
    wx.reLaunch({
      url: '../index?pt=complete',
    })
  },
  //跳转到京东
  toJD: function () {
    var that = this;
    let adType = that.data.adType;
    let adPath = that.data.adPath;
    if (adType == 2) {
      wx.navigateToMiniProgram({
        appId: 'wx91d27dbf599dff74',
        path: adPath,
        success: function (res) {
          that.recordAd('success');
        },
        fail: function (res) {
          console.log("打开失败...", res)
          that.recordAd('fail');
        }
      })
    } else if (adType == 3) {
      // 跳转到网页
      wx.navigateTo({
        url: '../webView/webView?adPath=' + encodeURIComponent(adPath),
      })
      that.recordAd('success');
    } else {
      that.recordAd('fail');
    }
  },
  //清除图片缓存
  getCurrentUrl: function (url) {
    if (!url) {
      return "";
    }
    var getTimestamp = new Date().getTime();
    if (url.indexOf("?") > -1) {
      url = url + getTimestamp
    } else {
      url = url + "?" + getTimestamp
    }
    return url;
  },
  //记录归位桩蓝牙连接错误日志
  recordAd: function (action) {
    var that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/weixin/optTipAd',
        method: 'post',
        headers: header,
        data: {
          userId: that.data.userId,
          adId: that.data.adId, //广告id，对应广告标题
          miniPro: 'wx', //wx：微信小程序；ali：支付宝小程序
          tipPage: that.data.tipPage, //rent：租借；back：归还
          action: action //read：展示；success：成功跳转；fail：取消跳转--仅小程序跳转有fail
        },
        success: function (res) {
          console.log("日志记录成功")
        },
        fail: function (res) {
          console.log("日志记录失败")
        }
      })
    })
  },
  registerAudioContext: function () {
    this.innerAudioContext = wx.createInnerAudioContext();
    if (wx.getStorageSync('no_pay_deposit') && wx.getStorageSync('no_pay_deposit') == '1') {
      var voicePath = this.data.duanyuyin;
      this.setData({
        showTitle: false
      })
    } else {
      var voicePath = this.data.voiceTempFilePath;
      this.setData({
        showTitle: true
      })
    }
    this.innerAudioContext.src = voicePath;

    this.innerAudioContext.play();

    this.innerAudioContext.onEnded((res) => {
      console.log('播放结束!');
    })

    this.innerAudioContext.onError((res) => {
      console.log('播放音频失败' + res);
    })

    this.innerAudioContext.onStop((res) => {
      console.log('停止播放!');
    })

  },
  // 租借播报
  registerAudioContexted: function () {

    this.innerAudioContext = wx.createInnerAudioContext();
    var voicePath = this.data.yuyinzujie;
    this.innerAudioContext.src = voicePath;

    this.innerAudioContext.play();

    this.innerAudioContext.onEnded((res) => {
      console.log('播放结束!');
    })

    this.innerAudioContext.onError((res) => {
      console.log('播放音频失败' + res);
    })

    this.innerAudioContext.onStop((res) => {
      console.log('停止播放!');
    })

  },
  /**
   * 获取基本的配置信息
   */
  getBasicConfigInfo() {
    var that = this
    if (app.globalData.isAllowBroadcastBack === 0) {
      that.setData({
        loading_show: false
      })
    }
    var systemInfo = wx.getStorageSync('systeminfo')
    var phoneType = ''
    if (systemInfo) {
      phoneType = systemInfo.model
    }
    var boxStopTimer = null;

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/base_config',
        method: 'post',
        header: header,
        data: {
          phoneType: phoneType
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            that.setData({
              loading_show: false
            })
            return
          }
          var config = JSON.parse(res.data)

          // 如果服务器返回了登录页面默认是否勾选同意按钮的配置，则将服务器下发的配置覆盖保存到本地全局配置
          if (config.defCheckAgreeService != undefined) {
            app.globalData.defCheckAgreeService = config.defCheckAgreeService == 1
          }

          if (config.miniBeeConfig) {
            app.globalData.miniBeeConfig = config.miniBeeConfig
          } else {
            app.globalData.miniBeeConfig = null
          }

          console.log('【小蜜蜂广告配置】最新的广告配置...' + JSON.stringify(app.globalData.miniBeeConfig))

          if (that.data.leaseSuc) {

            // 记录展示关注公众号日志
            if (!app.globalData.isSubOffical) {
              app.recordShowMpLog(-200004, '关注公众号-租借成功')
            }

            util.bee_record_page_uv('用户租借成功', '/pages/index/lease_tip/lease_tip')
            if (app.globalData.miniBeeConfig && app.globalData.miniBeeConfig.lease_success) {
              if (app.globalData.miniBeeConfig.lease_success.active == 1) {
                util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'read')
              }
              that.setData({
                beeBannerConfig: app.globalData.miniBeeConfig.lease_success
              })
            }
          } else if (that.data.backtime) {

            // 记录展示关注公众号日志
            if (!app.globalData.isSubOffical) {
              app.recordShowMpLog(-200005, '关注公众号-归还成功')
            }

            util.bee_record_page_uv('用户归还成功', '/pages/index/lease_tip/lease_tip')
            if (app.globalData.miniBeeConfig && app.globalData.miniBeeConfig.return_success) {
              if (app.globalData.miniBeeConfig.return_success.active == 1) {
                util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30001, '归还成功-小蜜蜂弹窗广告', 'read')
              }
              that.setData({
                beeModalConfig: app.globalData.miniBeeConfig.return_success
              })
              setTimeout(() => {
                that.setData({
                  showBeeModal: true
                })
              }, 100)
            }
          }

          console.log('base_config-->', config);
          if (config.scan_time) {
            let tempArr = config.scan_time.split(',');
            console.log('tempArr-->', tempArr);
            if (tempArr[0]) {
              that.data.scanTime = tempArr[0];
            }
          }
          BLELocker.scanBox();
          boxStopTimer = setTimeout(() => {
            that.setData({
              loading_show: false
            })
            BLELocker.findDevStopDiscovery('lease_tip');
          }, that.data.scanTime)
        },
        fail: function (res) {
          if (boxStopTimer) {
            clearTimeout(boxStopTimer);
          }
          that.setData({
            loading_show: false
          })
          BLELocker.findDevStopDiscovery('lease_tip');
        }
      })

    });

  },

  rejectSubWxMsg: function () {
    this.setData({
      wxSubMsgTipAlert: false
    });
  },

  agreeSubWxMsg: function () {
    this.setData({
      wxSubMsgTipAlert: false
    });
    console.warn('requestSubscribeMessage-开始发起租借成功的订阅消息');
    let tmplIds = ['KnUsFuS2NB07Pf9xbznQlyK_qZOU7DxOFl8l6E26Nww', '-S91jtVpX2Vto5EyXauKW008LYSSbsZiI8IWdepDarE', 'Ojc2ykpjZCmudn04IfG5M-3_1SBwzkrrSGHy7B68_Ig', 'neMTKZJgUrp9cHl4OVE9pTRiPs3nWYtGR2SHVY1ix58'];
    let acceptIds = [];
    wx.requestSubscribeMessage({
      tmplIds: tmplIds,
      success(res) {
        let acceptIds = [];
        for (let i = 0; i < tmplIds.length; i++) {
          res[tmplIds[i]] == 'accept' ? acceptIds[i] = 1 : acceptIds[i] = 0;
        }
        app.executeRequest((header) => {
          wx.request({
            url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
            method: 'post',
            header: header,
            data: {
              acceptIds: JSON.stringify(acceptIds)
            }
          })
        })
      },
      complete(res) {
        console.warn('requestSubscribeMessage-租借成功', res, acceptIds);
        if (res.errCode == 20004) {
          wx.showModal({
            title: '提示',
            content: '需打开订阅消息权限,才能进行消息订阅',
            showCancel: false,
            success(res) {}
          })
        }
      },
      error: function (err) {
        console.warn('requestSubscribeMessage-Err', err, acceptIds);
      }
    })
  }

})